package com.letoken.platform.repo.admin.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.letoken.platform.pub.constant.AdminUserInfoConstant;
import com.letoken.platform.pub.util.BeanUtil;
import com.letoken.platform.repo.admin.res.user.AdminUserInfoRes;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Author: Shirley
 * @Date: 2022/1/6 19:56
 */
public class AdminUserInfoRedis {

    private StringRedisTemplate stringRedisTemplate;

    private AdminUserInfoRedis(){
        stringRedisTemplate = BeanUtil.getBean(StringRedisTemplate.class);
    }

    private enum Singleton{
        INSTANCE;
        private AdminUserInfoRedis instance;

        // JVM会保证此方法绝对只调用一次
        Singleton() {
            instance = new AdminUserInfoRedis();
        }
    }

    public static AdminUserInfoRedis me(){
        return Singleton.INSTANCE.instance;
    }

    /**
     * set
     *
     * @param key
     * @param value
     */
    public void setStr(String key, String value) {
        if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value)) {
            //向redis里存入数据和设置缓存时间
            stringRedisTemplate.opsForValue().set(key, value, AdminUserInfoConstant.TIMEOUT, TimeUnit.MINUTES);
        }
    }

    /**
     * set
     *
     * @param key
     * @param value
     */
    public void setObject(String key, Object value) {
        if (StringUtils.isNotBlank(key) && value != null) {
            String strValue = JSON.toJSONString(value);
            //向redis里存入数据和设置缓存时间
            stringRedisTemplate.opsForValue().set(key, strValue, AdminUserInfoConstant.TIMEOUT, TimeUnit.DAYS);
        }
    }

    /**
     * 获取字符串
     *
     * @param key
     * @return
     */
    public String getStrValue(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 获取对象
     *
     * @param key
     * @return
     */
    public AdminUserInfoRes getAdminUserInfo(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        String strValue = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(strValue)) {
            return null;
        }
        AdminUserInfoRes classRedis = null;
        try {
            classRedis = JSONObject.parseObject(strValue, AdminUserInfoRes.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return classRedis;
    }

    /**
     * 删除用户缓存
     *
     * @param key
     * @return
     */
    public Boolean delete(String key) {
        if (StringUtils.isNotBlank(key)){
            if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(key))){
                return stringRedisTemplate.delete(key);
            }
        }
        return false;
    }


}
